const sequelize = require("./dbConnect");
const md5 = require("md5");
const Admin = require("./modules/adminModule");
const Banner = require("./modules/bannerModule");
const BlogType = require("./modules/blogtypeModule.js");
const Blog = require("./modules/blogModule");
const Project = require("./modules/projectModule");
const Message = require("./modules/messageModule");
const About = require("./modules/aboutModule");
const Setting = require("./modules/settingModule");
//同步数据模型
(async function () {
  //模型关联

  //文章分类于文章
  BlogType.hasMany(Blog, { foreignKey: "categoryId", targetKey: "id" });
  Blog.belongsTo(BlogType, {
    foreignKey: "categoryId",
    targetKey: "id",
    as: "category",
  });
  //文章与文章评论
  Blog.hasMany(Message, { foreignKey: "blogId", targetKey: "id" });
  Message.belongsTo(Blog, {
    foreignKey: "blogId",
    targetKey: "id",
    as: "blog",
  });

  //同步模型
  await sequelize.sync({
    alter: true,
  });

  //管理员初始化
  const Admincount = await Admin.count();
  if (!Admincount) {
    const password = "123123";
    const userInfo = {
      name: "超级管理员",
      loginId: "admin",
      loginPwd: md5(password),
    };
    await Admin.create(userInfo);
    console.log(`初始化管理员已完成...`);
  }
  //首页标语初始化
  const Bannercount = await Banner.count();
  if (!Bannercount) {
    const bannerInfo = [
      {
        midImg: "/static/images/bg1-mid.webp",
        bigImg: "/static/images/bg1-big.webp",
        title: "叮当猫",
        description: "哆啦A梦",
      },
      {
        midImg: "/static/images/bg2-mid.webp",
        bigImg: "/static/images/bg2-big.webp",
        title: "钢之炼金术师",
        description: "钢之炼金术师",
      },
    ];
    await Banner.bulkCreate(bannerInfo);
    console.log("初始化首页标语已完成...");
  }
  //初始化关于页面
  const AboutCount = await About.count();
  if (!AboutCount) {
    const aboutInfo = {
      url: "https://baidu.com",
    };
    About.create(aboutInfo);
    console.log("关于页面初始化完成...");
  }
  //全局配置初始化
  const SettingCount = await Setting.count();
  if (!SettingCount) {
    const settingInfo = {
      avatar: "string",
      siteTitle: "string",
      github: "string",
      qq: "string",
      qqQrCode: "string",
      weixin: "string",
      weixinQrCode: "string",
      mail: "string",
      icp: "string",
      githubName: "string",
      favicon: "string",
    };
    await Setting.create(settingInfo);
    console.log("全局配置参数化完成...");
  }

  console.log("数据库初始化已完成");
})();
